package com.dingwen.treasure.manage.controller;

import com.dingwen.treasure.base.controller.BaseViewController;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.security.service.TokenService;
import com.dingwen.treasure.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登出API
 *
 * @author dingwen
 * @date 2022/11/28
 */
@Api(tags = "登出")
@RestController
@Slf4j
@RequestMapping("sys/logout")
public class SysLogoutController implements BaseViewController {

    @Resource
    private TokenService tokenService;

    /**
     * 注销 </br>
     * <ul>
     *     <li> 删除redis缓存</li>
     *     <li> 清除认证信息</li>
     * </ul>
     *
     * @return {@link Result}<{@link String}>
     */
    @GetMapping
    public Result<String> logout(HttpServletRequest request, HttpServletResponse response) {
        // 账号
        String account = SecurityUtils.getUsername();

        // 清除认证信息
        Authentication authentication = SecurityUtils.getAuthentication();
        new SecurityContextLogoutHandler().logout(
                request,
                response,
                authentication
        );
        tokenService.clearLoginInfo(account);

        return success();
    }
}
